package com.javalab.recorder;

import java.io.File;
import java.io.IOException;

import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.TargetDataLine;

public class SoundRecordThread extends Thread {

	private TargetDataLine targetDataLine;

	private AudioFormat audioFormat;

	private AudioFileFormat.Type targetType;

	private File outputFile;

	public SoundRecordThread(TargetDataLine targetDataLine, AudioFormat audioFormat, AudioFileFormat.Type targetType, File outputFile) {
		this.targetDataLine = targetDataLine;
		this.audioFormat = audioFormat;
		this.targetType = targetType;
		this.outputFile = outputFile;
	}

	public void startRecording() {
		try {
			targetDataLine.open(audioFormat);
			targetDataLine.start();
			super.start();
		} catch (LineUnavailableException e) {
			e.printStackTrace();
		}
	}

	public void stopRecording() {
		targetDataLine.stop();
		targetDataLine.close();
	}

	@Override
	public void run() {
		try {
			AudioSystem.write(new AudioInputStream(targetDataLine), targetType, outputFile);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void setTargetDataLine(TargetDataLine targetDataLine) {
		this.targetDataLine = targetDataLine;
	}

	public void setOutputFile(File outputFile) {
		this.outputFile = outputFile;
	}

	public void setTargetType(AudioFileFormat.Type targetType) {
		this.targetType = targetType;
	}

	public void setAudioFormat(AudioFormat audioFormat) {
		this.audioFormat = audioFormat;
	}

}
